package com.bdsy.business.controller;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.bdsy.api.annotation.IgnoreAuth;
import com.bdsy.business.model.UserInfo;
import com.bdsy.business.model.UserIntegrals;
import com.bdsy.business.service.UserInfoService;
import com.bdsy.business.service.UserIntegralsService;
import com.bdsy.common.annotation.Json;
import com.bdsy.common.utils.Result;
import com.bdsy.common.utils.StringUtil;
import com.bdsy.common.utils.UUIDUtil;
import com.bdsy.system.annotation.SysLog;
import com.bdsy.system.model.User;
import com.bdsy.system.model.UserRole;
import com.bdsy.system.service.UserRoleService;
import com.bdsy.system.service.UserService;
import com.bdsy.system.shiro.Encrypt;

/**
 * 用户信息
 * @author MING
 * @date 2018年1月4日 上午11:47:31
 */
@Controller
@RequestMapping(value = {"${web.adminPath}", "${web.appPath}"})
public class UserInfoController {

	@Autowired
	UserInfoService userInfoService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	UserRoleService userRoleService;
	
	@Autowired
	UserIntegralsService userIntegralsService;   
	
	/**
	 * 查询用户信息
	 */
	@IgnoreAuth
	@Json
	@RequestMapping(value = "selectUserInfoById")
	public Object selectUserInfoById(String userId) {
		Map<String,Object> map = new LinkedHashMap<>();
		List<UserInfo> userInfo = userInfoService.selectUserInfoById(userId);
		map.put("code", 200);
		map.put("msg", "success");
		map.put("data", userInfo);
		return map;
	}
	
	
	/**
	 * 修改用户信息
	 */
	@IgnoreAuth
	@Json
	@RequestMapping(value = "updateUserInfo")
	public Object updateUserInfo(UserInfo userInfo,User user,MultipartFile file) {
		boolean result = userInfoService.updateUserInfo(userInfo, file);
		//修改用户名
		user.setUserStatus(1);
		boolean result2 = userService.updateUser(user);
		if (result && result2) {
			return Result.ok("updateSuccess");
		} else {
			return Result.error("updateFail");
		}
	}
	
	
	/**
	 * 短信验证码
	 */
	@Json
	@RequestMapping(value = "vCode")
	public Object vCode() {
		Map<String,Object> map = new LinkedHashMap<>();
//		String randomCode = RandomUtils.generate(4);
		String randomCode = "1234";
		map.put("code", 200);
		map.put("msg", "success");
		map.put("vCode", randomCode);
		return map;
		
	}
	
		
	
	/**
	 * 新增用户
	 */
	@Json
	@RequestMapping(value="addUserInfo")
	public Object addUserInfo(User user,UserInfo userInfo,UserRole userRole,String roleId) {
		//判断用户名是否唯一
		User u = userService.getUsername(user.getLoginName().trim());
		String userId;
		if(u == null){
			user.setUserStatus(1);
			boolean flag = true;
			do {
				userId = UUIDUtil.randomUUID();
				User dbUser = userService.getUserById(userId);
				//如果用户id唯一，则直接赋值，不唯一要重新生成用户id
				if(dbUser == null){
					flag = false;
					user.setUserId(userId);
				}
			} while (flag);
			user.setCreateDate(new Date());
			//去掉输入框的错误输入的空格
			user.setLoginName(StringUtil.replaceBlank(user.getLoginName()));
			user.setLoginPassword(user.getLoginPassword().trim());
			String pwd = Encrypt.md5(user.getLoginPassword(), user.getLoginName());
			user.setLoginPassword(pwd);
			String userName = "by_"+ userId;
			user.setUserName(userName);
			boolean result = userService.addUser(user);
			userInfo.setUserId(userId);
			userInfo.setPhone(user.getLoginName());
			boolean result2 = userInfoService.addUserInfo(userInfo);
			if (result && result2) {
				userRole.setUserRoleId(UUIDUtil.randomUUID());
				userRole.setUserId(userId);
				roleId = "2";
				userRole.setRoleId(roleId);
				userRoleService.addUserRole(userRole);
				//积分
				UserIntegrals userIntegrals = new UserIntegrals();
				userIntegrals.setUserId(userId);
				userIntegralsService.insert(userIntegrals);
				return Result.ok("注册成功");
			}else{
				return Result.error("注册失败");
			}
		}else{
			return Result.error("用户名已存在!");
		}
	}
	
	
	/**
	 * 修改密码
	 */
	@IgnoreAuth
	@Json
	@RequestMapping(value="/updatePassword")
	public Result  updatePassword(User user,String newPassword){
		
		boolean result=false;
		String loginPassword = userService.getLoginPasswordById(user.getUserId());
		String oldPassword = Encrypt.md5(user.getLoginPassword(), user.getLoginName());
		//对比旧密码输入是否正确
		if(!oldPassword.equals(loginPassword)){
			return Result.error("原密码错误!");
		}else{
			if(loginPassword !=null && newPassword.trim().length()>0){
				String encryptLoginPassword=Encrypt.md5(newPassword, user.getLoginName());
				if(!encryptLoginPassword.equals(user.getLoginPassword())){
				user.setLoginPassword(encryptLoginPassword);
				result = userService.updateUser(user);
				}
			}
		}
		if (result) {
    		return Result.ok("密码修改成功,请重新登录!");
		}else{
			return Result.error("密码修改失败!");
		}
	}
	
	
	
	
	/**
	 * 忘记密码
	 */
	@Json
	@RequestMapping(value="/forgetPassword")
	public Result  forgetPassword(User user){

		// 判断手机号 LoginName 是否存在
		User u = userService.getUsername(user.getLoginName());
		if(u == null){
			return Result.error("该手机号不存在");
		}else{
			String encryptLoginPassword=Encrypt.md5(user.getLoginPassword(), user.getLoginName());
			user.setLoginPassword(encryptLoginPassword);
			boolean result = userService.updatePassWord(user);
			
			if (result) {
				return Result.ok("密码修改成功,请重新登录!");
			}else{
				return Result.error("密码修改失败!");
			}
		}
	}
	
	
	
	
	
	/**
	 * 换绑手机号
	 */
	@IgnoreAuth
	@Json
	@RequestMapping(value="/updatePhone")
	public Result  updatePhone(User user,UserInfo userInfo,String newPhone){
		if(userInfo.getPhone() == newPhone){
			return Result.error("手机号与原手机号一致!");
		}
		userInfo.setPhone(newPhone);
		boolean result = userInfoService.updateUserInfo(userInfo, null);
		user.setLoginName(newPhone);
		boolean result2 = userService.updateUser(user);
		if (result && result2) {
    		return Result.ok("手机号换绑成功,请重新登录!");
		}else{
			return Result.error("手机号换绑修改失败!");
		}
	}
	
	
}
